{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Internal Datastructure: Bus branch model, Admittance and Jacobian Matrix\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This jupyter notebooks explains how to access and interpret the internal datastructure with relevant matrices."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Internal Datastructure\n",
    "\n",
    "We use the simple example network from the create_simple tutorial as an example for how to access internal calculation parameters:\n",
    "\n",
    "<img src=\"pics/example_network_simple.png\">\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandapower.run import runpp, rundcpp\n",
    "from pandapower.networks import example_simple, create_cigre_network_mv\n",
    "from pandapower.plotting.collections import (\n",
    "    create_bus_bus_switch_collection,\n",
    "    create_bus_collection,\n",
    "    create_ext_grid_collection,\n",
    "    create_line_collection,\n",
    "    create_trafo_collection,\n",
    "    create_line_switch_collection,\n",
    "    create_load_collection,\n",
    "    draw_collections\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "net = example_simple()\n",
    "print(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, we run a power flow in this network:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "runpp(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When a power flow is carried out, the element based grid model is translated into a bus-branch model. That bus-branch model is stored in a data structure that is based on the PYPOWER/MATPOWER casefile (with some extensions). This ppc can be accesed after power flow:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "net._ppc"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For information on how this datastructure is defined, please refer to the MATPOWER documentation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** For linear power flow (DC load flow) 'Ybus' is no longer created, but 'Bbus' as a new 'internal' key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rundcpp(net)\n",
    "net._ppc['internal']['Bbus'].toarray()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nodal Point Admittance Matrix\n",
    "\n",
    "The nodal point admittance matrix is saved in the ppc and can be accessed directly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "runpp(net)\n",
    "net._ppc[\"internal\"][\"Ybus\"].todense()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the nodal point admittance matrix is given in per unit values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Jacobian Matrix\n",
    "\n",
    "The jacobian Matrix J in the last iteration step is also stored in the ppc and can be accessed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "net._ppc[\"internal\"][\"J\"].todense()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The jacobian matrix is also given in per unit values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mapping the Buses\n",
    "\n",
    "The pandapower indices are not equal to the ppc indices for several reasons. Some buses are fused together in case of closed bus-bus switches and auxiliary buses are created for elements like extended wards or three winding transformers.\n",
    "See here for more details: https://pandapower.readthedocs.io/en/latest/elements/switch.html\n",
    "\n",
    "There is however a mapping between pandapower indices and ppc indices that is created during the conversion to keep track of the dependencies that is also stored in the net:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "net._pd2ppc_lookups[\"bus\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a ppc index from the pandapower index, simply call the lookup like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pandapower_bus_idx = 3\n",
    "ppc_index = net._pd2ppc_lookups[\"bus\"][pandapower_bus_idx]\n",
    "print(ppc_index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, pandapower bus index 3 corresponds to ppc bus index 2. So if we would like to find the diagonal entry of the Ybus matrix for bus 2, we could now access it with that internal index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Ybus = net._ppc[\"internal\"][\"Ybus\"]\n",
    "int_idx = net._pd2ppc_lookups[\"bus\"][ppc_index]\n",
    "Ybus[int_idx, int_idx]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also see that some buses are mapped to the same internal bus, such as bus 1 and bus 2:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(net._pd2ppc_lookups[\"bus\"][1])\n",
    "print(net._pd2ppc_lookups[\"bus\"][2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That is because buses 1 and 2 are connected by a closed bus-bus switch and are therefore represented internally as the same bus:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "net.switch.loc[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Obtaining Jacobian Entries of Generators\n",
    "\n",
    "As an example we show how to obtain the Jacobian entries of generator buses using the pandapower -> ppc bus mapping. First we get buses of the in-service generators:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gen_buses = net.gen.loc[net.gen.in_service.values, \"bus\"].values\n",
    "print(f\"pandapower gen bus: {gen_buses}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Second, we geht the Jacobian matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "J = net._ppc[\"internal\"][\"J\"]\n",
    "print(f\"Jacobian shape: {J.shape}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why has the Jacobian the shape 9x9?\n",
    "It consists of the partial derivatives J11 = dP_dVa, J12 = dP_Vm, J21 = dQ_dVa, J22 = dQ_dVm. Except the reference bus, all PV- and PQ-buses are included in J. Vm is constant for PV nodes and dS/dVm is 0 for PV-buses (gens in pandapower) and Q is a variable. \n",
    "\n",
    "In our case we have 1 reference bus (at bus 0), 1 gen at bus 5, and 3 pq buses (at buses 1, 2, 4)\n",
    "\n",
    "This is the reason why J11 to J22  have these shapes:\n",
    "\n",
    "J11 = pvpq x pvpq (dP_dVa)\n",
    "\n",
    "J12 = pvpq x pq (dP_dVm)\n",
    "\n",
    "J21 = pq x pvpq (dQ_dVa)\n",
    "\n",
    "J22 = pq x pq (dQ_dVm)\n",
    "\n",
    "Only J11 contains values relevant for gens."
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Now we get the \"internal\" ppc buses with the lookup:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bus_lookup = ppc_index = net._pd2ppc_lookups[\"bus\"]\n",
    "print(f\"pandapower to ppc lookup: {bus_lookup}\")\n",
    "ppc_gen_buses = bus_lookup[gen_buses]\n",
    "print(f\"pandapower gen bus: {gen_buses} maps to ppc gen bus: {ppc_gen_buses}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we need the pv and pq entries in J to obtain the Jacobian sub-matrices:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# get pv and pq values from newtonpf()\n",
    "pv = net._ppc[\"internal\"][\"pv\"]\n",
    "pq = net._ppc[\"internal\"][\"pq\"]\n",
    "# stack these as done in newtonpf()\n",
    "pvpq = np.hstack((pv, pq))\n",
    "\n",
    "print(\"pv and pq nodes as in the newtonpf() function\")\n",
    "print(f\"pv buses: {pv}\\npq buses: {pq}\\npvpq buses: {pvpq}\")\n",
    "\n",
    "# get len of pv and pq\n",
    "n_pvpq = len(pvpq)\n",
    "n_pq = len(pq)\n",
    "n_pv = len(pv)\n",
    "# get J11, J12, J21, and J22\n",
    "j11 = J[:n_pvpq, :n_pvpq]\n",
    "j12 = J[:n_pvpq, n_pvpq:]\n",
    "j21 = J[n_pvpq:, :n_pvpq]\n",
    "j22 = J[n_pvpq:, n_pvpq:]\n",
    "\n",
    "print(\"shape of J sub-matrices:\")\n",
    "print(f\"j11 = {j11.shape}\")\n",
    "print(f\"j12 = {j12.shape}\")\n",
    "print(f\"j21 = {j21.shape}\")\n",
    "print(f\"j22 = {j22.shape}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we finally get the generator entries in J:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# j11 gen entries\n",
    "m = np.isin(pvpq, pv)\n",
    "n = m\n",
    "\n",
    "j11_gen_entries = j11[m, n]\n",
    "print(f\"J11 indices: m = {m}, n = {n}\")\n",
    "print(f\"pandapower gen {gen_buses} entries (ppc PV nodes {ppc_gen_buses}) in J11 (=dP/dVa): {j11_gen_entries}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visiualizing the Matrices\n",
    "You can easily visualize the matrices with matplotlib and the plot function spy(). Let's look at an example.\n",
    "\n",
    "First, we define a plot function to visiualize the sparse Ybus matrix (works also with any other matrix like J) including some labels:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as mpl\n",
    "import numpy as np\n",
    "\n",
    "from pandapower.plotting import get_collection_sizes\n",
    "\n",
    "def plot_ybus(net=None, ax=None, ybus=None):\n",
    "    if ax is None:\n",
    "        fig, ax = mpl.subplots(1, 2)\n",
    "    if ybus is None:\n",
    "        ybus = net._ppc[\"internal\"][\"Ybus\"]\n",
    "    ax.spy(ybus)\n",
    "    ax.set_title(\"Ybus shape {}\\n\".format(str(ybus.shape)))\n",
    "    ax.set_xticks(np.arange(ybus.shape[0]))\n",
    "    ax.set_xticklabels(np.arange(ybus.shape[0]))\n",
    "    ax.set_yticklabels(np.arange(ybus.shape[1]))\n",
    "    ax.set_yticks(np.arange(ybus.shape[1]))\n",
    "\n",
    "    ax.grid(which=\"both\", linestyle=\"dotted\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Second, we define a function to plot the power system including some bus labels and other collections:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_net(net, ax=None):\n",
    "    import geojson\n",
    "    if ax is None:\n",
    "        fig, ax = mpl.subplots(1, 1, figsize=(10, 8))\n",
    "\n",
    "    sizes = get_collection_sizes(net)\n",
    "\n",
    "    # create collections for elements\n",
    "    collections = [\n",
    "        create_bus_collection(net, size=sizes[\"bus\"]),\n",
    "        create_line_collection(net, use_bus_geodata=True),\n",
    "        create_trafo_collection(net, size=sizes[\"trafo\"]),\n",
    "        create_ext_grid_collection(net, size=sizes[\"ext_grid\"], orientation=1.5),\n",
    "        create_bus_bus_switch_collection(net, size=sizes[\"switch\"]),\n",
    "        create_line_switch_collection(net, distance_to_bus=sizes[\"switch_distance\"], size=sizes[\"switch\"]),\n",
    "        create_load_collection(net, size=sizes[\"load\"])\n",
    "    ]\n",
    "\n",
    "    # add labels for each bus\n",
    "    for idx in net.bus.geo.index:\n",
    "        x, y = geojson.loads(net.bus.loc[idx, 'geo']).coordinates \n",
    "        y += sizes[\"bus\"] * 1.\n",
    "        ax.text(x, y, str(idx), fontsize=12, color=\"r\")\n",
    "\n",
    "    draw_collections(collections, ax=ax)\n",
    "    mpl.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Third, we create a plot function with three subplots. The first subplots shows the power system including the bus labels. The second and third plot shows the Ybus matrix with different settings. If you just call runpp() the buses are fused internally and the Ybus matrix has a lower dimension. You can also use the parameter `r_switch` to set impedance values for switches. In this case, the buses are not fused and the Ybus matrix has a higher dimension. This also changes your power flow result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_overview(net):\n",
    "    fig, axes = mpl.subplots(1, 3, figsize=(16, 8))\n",
    "    runpp(net)\n",
    "    plot_net(net, ax=axes[0])\n",
    "    # plot y bus with max. const shape (no fused switches)\n",
    "    runpp(net, check_connectivity=False, r_switch=0.1, init=\"flat\", neglect_open_switch_branches=True)\n",
    "    plot_ybus(net, ax=axes[1])\n",
    "    # plot ybus for power flow (with fused switches)\n",
    "    runpp(net)\n",
    "    plot_ybus(net, ax=axes[2])\n",
    "    mpl.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we call the overview function with the cigre example power system:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "net = create_cigre_network_mv()\n",
    "plot_overview(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each dot in the spy plot is ea"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
